<template>
    <div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px">
            <el-form-item label="优惠券名称" prop="name">
                <el-input v-model="ruleForm.name" style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item label="优惠券类型" prop="type">
                <el-radio v-model="ruleForm.type" label="FIXED">满减券</el-radio>
                <el-radio v-model="ruleForm.type" label="PERCENT">折扣券</el-radio>
            </el-form-item>
            <div class="fl">
                <el-form-item label="使用门槛" prop="threshold">
                    <el-input v-model="ruleForm.threshold"></el-input>
                </el-form-item>
                <el-form-item label="折扣" prop="discount" style="width: 330px; margin-left: 60px;" v-if="ruleForm.type == 'PERCENT'">
                    <el-input placeholder="0-10之间，允许小数" v-model="ruleForm.discount">
                        <template slot="append">折</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="优惠金额" prop="discount" style="margin-left: 60px;" v-else>
                    <el-input v-model="ruleForm.discount"></el-input>
                </el-form-item>
            </div>
            <div class="fl">
                <el-form-item label="优惠券库存" prop="totalQuantity">
                    <el-input v-model="ruleForm.totalQuantity" placeholder="输入-1表示不限量"></el-input>
                </el-form-item>
                <el-form-item label="每人限领数量" prop="limitPerUser" style="margin-left: 60px;">
                    <el-input v-model="ruleForm.limitPerUser"></el-input>
                </el-form-item>
            </div>
            <!-- <el-form-item label="有效期类型" prop="validityType">
                <el-radio v-model="ruleForm.validityType" label="FIXED">固定日期</el-radio>
                <el-radio v-model="ruleForm.validityType" label="DYNAMIC">领取后X天内有效</el-radio>
            </el-form-item> -->
            <el-form-item label="有效期时间" prop="endTime" v-if="ruleForm.validityType == 'FIXED'">
                <el-date-picker v-model="selectDate" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" @change="dateChange"></el-date-picker>
            </el-form-item>
            <el-form-item label="领取后有效天数" prop="daysAfterClaim" v-else>
                <el-input v-model="ruleForm.daysAfterClaim" style="width: 300px;"></el-input>
            </el-form-item>
            <!-- <el-form-item label="使用场景" prop="scene">
                <el-radio v-model="ruleForm.scene" label="COMMON">通用场景</el-radio>
                <el-radio v-model="ruleForm.scene" label="REGISTER">新用户注册</el-radio>
            </el-form-item> -->
            <el-form-item>
                <el-button type="primary" :loading="loading" @click="sub('ruleForm')">确定</el-button>
                <el-button @click="onCancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { apiCouponDetail, apiCouponEdit } from "@/api/coupon.js";
export default {
    name: "coupon_index_edit",
    props: {
        editId: {
            type: Number,
            required: true
        }
    },
    data() {
        return {
            ruleForm: {
                name: "", //优惠券名称
                type: "FIXED", //券类型：FIXED（满减）、PERCENT（折扣）、CASH（现金券）
                threshold: "", //使用门槛（满多少元可用）
                discount: "", //优惠金额/折扣比例
                totalQuantity: "", //总库存（-1表示不限量）
                limitPerUser: "", //每人限领张数
                validityType: "DYNAMIC", //有效期类型：FIXED（固定日期）、DYNAMIC（领取后N天有效）
                startTime: "", //有效期开始时间（validityType=FIXED时必填）
                endTime: "", //有效期结束时间（validityType=FIXED时必填）
                daysAfterClaim: "", //领取后有效天数（validityType=DYNAMIC时必填）
                scene: "COMMON", //使用场景（COMMON-通用场景 REGISTER-新用户注册 FOLLOW_MERCHANT-关注店铺）
                fundSource: "PLATFORM", //资金来源：PLATFORM（平台补贴）、MERCHANT（商家承担）
            },
            rules: {
                name: [{ required: true, message: "请输入优惠券名称", trigger: "change" }],
                type: [{ required: true, message: "请选择优惠券类型", trigger: "input" }],
                threshold: [{ required: true, message: "请输入使用门槛", trigger: "change" }],
                discount: [{ required: true, message: "请输入优惠金额/折扣比例", trigger: "change" }],
                totalQuantity: [{ required: true, message: "请输入总库存", trigger: "change" }],
                limitPerUser: [{ required: true, message: "请输入每人限领张数", trigger: "change" }],
                validityType: [{ required: true, message: "请选择有效期类型", trigger: "change" }],
                startTime: [{ required: true, message: "请输入有效期开始时间", trigger: "change" }],
                endTime: [{ required: true, message: "请输入有效期结束时间", trigger: "change" }],
                daysAfterClaim: [{ required: true, message: "请输入领取后有效天数", trigger: "change" }],
                scene: [{ required: true, message: "请选择使用场景", trigger: "change" }],
            },
            loading: false,
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const start = new Date();
                        const end = new Date();
                        end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const start = new Date();
                        const end = new Date();
                        end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const start = new Date();
                        const end = new Date();
                        end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            selectDate: ''
        }
    },
    created() {
        this.getData()
    },
    watch: {
        editId() {
            this.getData()
        }
    },
    methods: {
        getData() {
            apiCouponDetail(this.editId).then(({ data }) => {
                if (data.type == 'PERCENT') {
                    data.discount = data.discount * 10
                }
                this.ruleForm = data
                if (data.startTime) {
                    this.selectDate = [data.startTime, data.endTime]
                }
            })
        },
        dateChange(e) {
            if (e) {
                this.ruleForm.startTime = e[0]
                this.ruleForm.endTime = e[1]
            } else {
                this.ruleForm.startTime = ''
                this.ruleForm.endTime = ''
            }
        },
        // 确定
        sub(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.ruleForm.validityType == 'FIXED') {
                        const date = new Date(this.ruleForm.startTime).getTime()
                        const now = new Date().getTime()
                        if (now - date > 0) {
                            this.$message({ message: "有效期时间只能选择未来时间段", type: "error" });
                            return
                        }
                    } else {
                        this.ruleForm.startTime = ''
                        this.ruleForm.endTime = ''
                    }
                    this.loading = true;
                    const postData = JSON.parse(JSON.stringify(this.ruleForm))
                    if (postData.type == 'PERCENT') {
                        postData.discount = (postData.discount / 10).toFixed(2)
                    }
                    apiCouponEdit(this.editId, postData).then((res) => {
                        this.loading = false;
                        if (res.code == 200) {
                            this.$message({ message: "操作成功", type: "success" });
                            this.$emit("onSubmit");
                        }
                    }).catch((err) => {
                        this.loading = false;
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        // 取消
        onCancel() {
            this.loading = false;
            this.$emit("onCancel");
        },
        // 重置
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    },
}
</script>

<style></style>